import axios from "axios";


import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/user/user.js";
import router from "@/router/index.js";

const request =axios.create({
    baseURL:'http://localhost:8080/api'
})
//request.defaults.withCredentials=true
const logout=()=>{
    useUserStore().logout();
    router.push('/')
}
/**
 * 请求拦截器
 */
request.interceptors.request.use(
    (config) => {
        const userStore=useUserStore()
        const token=userStore.token
        if(token){
            config.headers.Authorization=token;
        }
        return config
    },
    (err) => Promise.reject(err)
)
/**
 * 响应拦截器
 */
request.interceptors.response.use( (response)=> {
    // apiData 是 api 返回的数据
    const apiData = response.data
    //console.log(apiData)
    // 二进制数据则直接返回
    const responseType = response.request?.responseType
    if (responseType === "blob" || responseType === "arraybuffer") return apiData

    if (apiData===401){
        logout()
    }else {
        return apiData
    }

},(error) => {
    ElMessage.error(error.errMsg)
    return Promise.reject(error)
});

export default request
